package com.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.*;
import java.util.logging.Logger;

public class PostUtil {
    private static final Logger logger = Logger.getLogger(PostUtil.class.getName());
    private final String PLATFORM_URI = "https://fdlpfjk.vecc.org.cn";

    public static void main(String[] args) {
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        Map<String,String> map = new HashMap<>();
//        String url = "/nrmm-api/record/login";
//        map.put("username","fw3umfi36a0o");
//        map.put("password","39bu9peu");
//        String url = "/nrmm-api/system/terminalrecord/outside/findAll";
//        headerMap.put("X-Access-Token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2OTQ1ODc2NzcsInVzZXJuYW1lIjoiZnczdW1maTM2YTBvIn0.lpAg8i4XS7NlnIon9reVJFsePs8MJdCzDHuIOoj-ODg");
//        map.put("tboxType","T-BOX-00109");
//        String bodyData = JSONObject.toJSONString(map);
//        String result = new PostUtil().post(url,paramMap,headerMap,bodyData);
//        System.out.println("result :" + result);
        getAreaTest();

    }
    public  String post(String url, Map<String, Object> paramMap, Map<String, Object> headerMap,
                               String bodyData) {
        /**
         * 携带Cookies、参数、Header的POST请求
         */
        try {
            // 1:----设置传递参数----
//            url = PLATFORM_URI+url;
            System.out.println("+++++++++++++++请求地址2222： " + url);
            // 创建post对象
            HttpPost post = new HttpPost(url);
            // 创建集合 添加参数
            List<NameValuePair> list = new LinkedList<NameValuePair>();
            if (!paramMap.isEmpty()) {
                for (String key : paramMap.keySet()) {
                    BasicNameValuePair param = new BasicNameValuePair(key, paramMap.get(key).toString());
                    list.add(param);
                }
                UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "utf-8");
                post.setEntity(entityParam);
            }

            // 使用URL实体转换工具
            if (StringUtils.isNotBlank(bodyData)) {
                post.setEntity(new StringEntity(bodyData, "UTF-8"));
            }

            // 2:----设置Header信息----
            // 设置Headers头信息
            if (!headerMap.isEmpty()) {
                for (String key : headerMap.keySet()) {
                    post.addHeader(key, headerMap.get(key).toString());
                }
            }
            post.setHeader("Content-Type", "application/json;");
            HttpClient client = HttpClients.custom().build();
            // 执行Post请求
            HttpResponse response = client.execute(post);
            // 将response对象转换成String类型
            String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
//            System.out.println("========: " + responseStr);
            return responseStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void getAreaTest(){
        List<String> list = new ArrayList<>();
        String filePath = "d:/test/imei2.txt";
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        list.add("864601064552755");
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        Map<String,String> map = new HashMap<>();
        for(int j=0;j<list.size();j++) {
            int index = j+1;
            System.out.println("===============已发： " + index);
            String imei = list.get(j);
//            String imei = "864601064536758";
            float totalArea = 0;
            boolean flag = true;
            try {
                int p = 1;
                while (flag) {
                    String url = "http://nj2wm.cn/scan/record?p=" + p + "&imei=" + imei;
                    String bodyData = JSONObject.toJSONString(map);
                    String result = new PostUtil().post(url, paramMap, headerMap, bodyData);
                    System.out.println("result :" + result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    int status = jsonObject.getInteger("status");
                    if (status == 111111) {
                        JSONArray array = jsonObject.getJSONArray("stat_iot_day");
                        if (array.size() > 0) {
                            for (int i = 0; i < array.size(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                float area = object.getFloat("area");
                                totalArea += area;
                            }
                            p++;
                        } else {
                            flag = false;
                        }
                    } else {
                        flag = false;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                totalArea = - 1;
            }

            System.out.println("imei:" + imei + ";area:" + totalArea);
            String content = imei+"-"+totalArea;
            String file = "d:/test/area2.txt";
            try {
                // 创建FileWriter对象
                FileWriter fileWriter = new FileWriter(file, true);

                // 创建BufferedWriter对象
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

                // 写入内容
                bufferedWriter.write(content);
                bufferedWriter.newLine();

                // 关闭BufferedWriter和FileWriter
                bufferedWriter.close();
                fileWriter.close();

                System.out.println("写入成功！");
            } catch (IOException e) {
                System.out.println("写入失败：" + e.getMessage());
            }
        }
    }
}
